

# 导入数据请求模块
import requests
# 导入正则表达式模块
import re
# 导入json模块
import json
# 导入格式化输出模块
from pprint import pprint
# 导入自动化测试模块
from selenium import webdriver
# 导入时间模块
import time
from selenium.webdriver.common.by import By
from urllib.parse import unquote
import os



def downLoadWithUrl(id):     
    try:
        """发送请求"""
        # 请求链接  
        url = f'https://www.douyin.com/user/MS4wLjABAAAAkzRSrOuSsM4Z1Ricsddumx_aSvX0jmOPcQR2qTs3PEtImBD8BomLrqvtIOBKOL0P?modal_id={id}'
        # 模拟浏览器
        headers = {
            'Cookie':'douyin.com; device_web_cpu_core=6; device_web_memory_size=8; architecture=amd64; ttwid=1%7C8G9r9pAsU1aFzyYoAs4EBGgadS1fnfN4y_SE0U2tIE4%7C1697284289%7C369d1bcedd8138537de4b27a0d7e3008ae22b227f75ad0419180418943ea2cb2; passport_csrf_token=def783dda3cef72e8aa8501bba5ebbee; passport_csrf_token_default=def783dda3cef72e8aa8501bba5ebbee; s_v_web_id=verify_lnpz8tcd_3XM8GNhT_C2e5_4oeW_9QQ1_IK6DhXGG8bsP; my_rd=2; webcast_local_quality=null; stream_recommend_feed_params=%22%7B%5C%22cookie_enabled%5C%22%3Atrue%2C%5C%22screen_width%5C%22%3A2560%2C%5C%22screen_height%5C%22%3A1440%2C%5C%22browser_online%5C%22%3Atrue%2C%5C%22cpu_core_num%5C%22%3A6%2C%5C%22device_memory%5C%22%3A8%2C%5C%22downlink%5C%22%3A10%2C%5C%22effective_type%5C%22%3A%5C%224g%5C%22%2C%5C%22round_trip_time%5C%22%3A50%7D%22; FORCE_LOGIN=%7B%22videoConsumedRemainSeconds%22%3A180%7D; strategyABtestKey=%221699096969.067%22; home_can_add_dy_2_desktop=%221%22; bd_ticket_guard_client_data=eyJiZC10aWNrZXQtZ3VhcmQtdmVyc2lvbiI6MiwiYmQtdGlja2V0LWd1YXJkLWl0ZXJhdGlvbi12ZXJzaW9uIjoxLCJiZC10aWNrZXQtZ3VhcmQtcmVlLXB1YmxpYy1rZXkiOiJCSjVLdHNDZXVEV3VqZmgzbVdadVFHbmt0N3d0UkZvZDVnaWwyeCtBWnpLQ1lhZjRPMFp1VmFEOVUrM0JPdzJKMDMzQnp4dnRDQTNybEc5TktPZEZrek09IiwiYmQtdGlja2V0LWd1YXJkLXdlYi12ZXJzaW9uIjoxfQ%3D%3D; tt_scid=Mno41MB.hPdtiU56n66BAgjmiIsjkJxPjuFHELGCjJwS5.qHhAyaGyz1QDEV7Jwp74bf; download_guide=%221%2F20231104%2F0%22; pwa2=%220%7C0%7C1%7C0%22; msToken=t-1E36DVBPvQ-VI88HRX0r-bMp4W1RjgsOfMjbo0d0tb2d90jJex5nzwm4I3eWWZQ5V6Tob9FXrocb7CXN-FTivjsrLOEoKQAwfShjHv6j5MTamoihetw4kVqstdOKc=; volume_info=%7B%22isUserMute%22%3Afalse%2C%22isMute%22%3Atrue%2C%22volume%22%3A0.5%7D; msToken=5l5rrpzXZ2w4JvVJzxN3tM0D8WwPB2kQceEpYXbsI_XbWd98evzAOXBb8F86XuPoTupybcTVaKjLs_kRmr5-ur3sctIE9mu3uAOTG7kRKrcskLBRB0LurKsn09uALZA=; IsDouyinActive=false; __ac_nonce=06546354d00ccccfb94ee; __ac_signature=_02B4Z6wo00f01xhdY5gAAIDDmF-Z2bS5EV8YfWcAAKNbomfW3IMANqI2B9teCFXf2JYJnZFMyiomo3r.kRbkUITTnxiy2P4KrDBrlpv3QdhAmmoeEx1WR3W8OyGR1Lo0S-Dysh6wmfCN7tjY8a; __ac_referer=https://www.douyin.com/user/MS4wLjABAAAAkzRSrOuSsM4Z1Ricsddumx_aSvX0jmOPcQR2qTs3PEtImBD8BomLrqvtIOBKOL0P',
            'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/118.0.0.0 Safari/537.36'
        }
        # 发送请求
        response = requests.get(url=url, headers=headers)
        # response.encoding = 'utf-8'
        """获取响应数据"""
        html_data = unquote(response.text)
        """解析数据"""
        # print("html_data=============")
        # print(html_data)
        # 提取标题
        # restring = '\\\"desc\\\":\\\"(.*?)\\\",'
        restring = '\"desc\":\"(.*?)\",'
        print(restring)
        obj = re.compile(r'\"desc\":\"(.*?)\",')
        old_title = obj.findall(html_data)[0]

        # # old_title = re.findall('video_title" content="(.*?)"/>', html_data)[0]
        print(old_title)
        # # 替换特殊字符
        title =  old_title#re.sub(r'[\\/:*"?<>|\n]', '', old_title)
        print("title = ")
        print(title)
        # 视频链接信息
        result = re.findall('<script id="RENDER_DATA" type="application/json">(.*?)</script>', html_data)[0]
        # 解码
        info = requests.utils.unquote(result)
        # 转成json字典
        json_data = json.loads(info)
        print(json_data)
        # 提取视频链接 -> 字符串拼接 + 字典取值 + 列表索引取值
        video_url = 'https:' + json_data['app']['videoDetail']['video']['bitRateList'][0]['playAddr'][0]['src']
        print("video_url")
        print(video_url)
        """保存数据"""
        # 获取视频内容
        video_content = requests.get(url=video_url, headers=headers).content
        folderpath = "PythonDownLoad"
        if not os.path.exists(folderpath):
                    os.makedirs(folderpath)
        with open( folderpath + "/" + title + '.mp4', mode='wb') as f:
            f.write(video_content)
        print(title)
        pprint(video_url)
    except:
          pass
          
    
# downLoadWithUrl(7064550745437146383)
